const {
	search,
	searchBy,
	add,
	del
} = require('../js/mysql.js')

const router = require('koa-router')()
var jwtAuth = require("../jwtAuth")
const { dateFormat } = require('@jiess/utils');

router.prefix('/news')
router.use(jwtAuth)

// 查询所有新闻列表
router.get('/', async (ctx, next) => {
	// 获取页码数据，并指定默认值
	const { page, limit } = ctx.request.query;
	// 定义完整的带分页查询和模糊查询的数据库操作语句
	let sql1 = `select * from news LIMIT ${(page-1)*limit},${limit}`;
	let sql2 = `select count(id) as count from news`;
	// 获取完整的列表数据
	let data = await searchBy(sql1);
	// 查询条数
	let count = await searchBy(sql2);
	console.log(count[0].count, '===========');
	// 时间格式 
	let format = 'yyyy-MM-dd';
	ctx.body = {
		code:200,
		msg: '查询成功',
		data: data.map(item => {
			item.time = dateFormat(item.time, format)
			return item;
		}),
		count: count[0].count
	}
})

// 添加新闻
router.post('/', async (ctx, next) => {
	let {
		body
	} = ctx.request;
	let {
		title,
		author,
		time,
		isOnline,
		content
	} = body;
	let data = await add([title, author, time, isOnline, content], `news(title, author, time, isOnline, content) values(?,?,?,?,?)`);
	// console.log(data.affectedRows)
	if(data.affectedRows === 1) {
		ctx.body = {
			code: 200,
			msg: '添加新闻成功'
		}
	}else{
		ctx.body = {
			code: 514,
			msg: '添加新闻失败'
		}
	}
})

// 删除新闻
router.delete('/:id', async (ctx, next) => {
	console.log('=========')
	let { id } = ctx.params;
	console.log(id);
	let data = await del(`news where id = ${id}`);
	console.log(data);
	if(data.affectedRows > 0) {
		ctx.body = {
			code: 200,
			msg: '删除新闻成功'
		}
	}else{
		ctx.body = {
			code: 514,
			msg: '删除新闻失败'
		}
	}
})

// 更新新闻
router.put('/:id', async (ctx, next) => {
	let { id } = ctx.params;
	let { body } = ctx.request;
	let {
		title,
		author,
		time,
		isOnline,
		content
	} = body;
	let data = await edit(`news set title='${title}',author='${author}',time='${time}',isOnline='${isOnline}',content='${content}' where id=${id}`);
	if(data.affectedRows > 0) {
		ctx.body = {
			code: 200,
			msg: '更新新闻成功'
		}
	}else{
		ctx.body = {
			code: 514,
			msg: '更新新闻失败'
		}
	}
})

module.exports = router
